package com.cb.web.wasf.sample.web;

import com.cb.web.wasf.Message.FreeMessage;
import com.cb.web.wasf.State;
import com.cb.web.wasf.Request;
import com.cb.web.wasf.Principal;
import com.cb.web.wasf.StringUtils;
import com.cb.web.wasf.View;
import com.cb.web.wasf.View.JspView;

/**
 * @author CBO
 */
public class LoginState extends State {

    private String login;
    private String password;

    public LoginState() {
        login = "login";
        password = "password";
    }

    public String getLogin() {
        return login;
    }

    public String getPassword() {
        return password;
    }

    public State login(Request request) {
        clearMessages();
        this.login = request.getTrimmedParameter("login");
        this.password = request.getTrimmedParameter("password");
        boolean ok = true;
        if (StringUtils.isBlank(login)) {
            addMessage(new FreeMessage("Le champ identifiant est obligatoire"));
            ok = false;
        }
        if (StringUtils.isBlank(password)) {
            addMessage(new FreeMessage("Le champ mot de passe est obligatoire"));
            ok = false;
        }
        if (ok) {
            Principal principal = ManagerLocator.getUserManager().authenticate(login, password);
            if (principal == null) {
                addMessage(new FreeMessage("Indentifiant ou mot de passe incorrect"));
            } else {
                request.getSession().setPrincipal(principal);
                return new CartState();
            }
        }
        return this;
    }

    @Override
    public View getView() {
        return new JspView(this, "/WEB-INF/jsp/login.jsp");
    }
}
